<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listUser, getUser, addUser, updateUser, delUser } from '@/api/user'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 表格列配置
const columns = [
  { prop: 'userName', label: '用户名', width: '120' },
  { prop: 'gender', label: '性别', width: '80', formatter: (val) => (val === 0 ? '男' : '女') },
  { prop: 'phone', label: '联系电话', width: '120' },
  { prop: 'email', label: '邮箱', width: '180' },
  { prop: 'createTime', label: '注册时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['userName', 'phone', 'email']

// 表单数据
const formData = reactive({
  id: null,
  userName: '',
  password: '',
  gender: 0,
  phone: '',
  email: '',
  createTime: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = [
  { prop: 'userName', label: '用户名', type: 'input', required: true },
  { 
    prop: 'password', 
    label: '密码', 
    type: 'input', 
    inputType: 'password', 
    required: true,
    showPassword: true
  },
  { 
    prop: 'gender', 
    label: '性别', 
    type: 'radio', 
    options: [
      { label: '男', value: 0 },
      { label: '女', value: 1 }
    ]
  },
  { prop: 'phone', label: '联系电话', type: 'input' },
  { prop: 'email', label: '邮箱', type: 'input' }
]

// 表单字段配置 - 查看模式
const viewFormFields = [
  { prop: 'userName', label: '用户名', type: 'input', readonly: true },
  { 
    prop: 'gender', 
    label: '性别', 
    type: 'radio', 
    options: [
      { label: '男', value: 0 },
      { label: '女', value: 1 }
    ],
    disabled: true
  },
  { prop: 'phone', label: '联系电话', type: 'input', readonly: true },
  { prop: 'email', label: '邮箱', type: 'input', readonly: true },
  { 
    prop: 'createTime', 
    label: '注册时间', 
    type: 'input', 
    readonly: true,
    formatter: formatDateTime
  }
]

// 表单规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '添加用户',
  isEdit: false,
  isView: false
})

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    tableData.value = await listUser()
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 添加用户
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'gender' ? 0 : ''
  })
  formData.id = null
  
  dialogConfig.title = '添加用户'
  dialogConfig.isEdit = false
  dialogConfig.isView = false
  dialogConfig.visible = true
}

// 编辑用户
const handleEdit = async (row) => {
  try {
    const res = await getUser(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key]
      })
      
      dialogConfig.title = '编辑用户'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 查看用户
const handleView = async (row) => {
  try {
    const res = await getUser(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key]
      })
      
      dialogConfig.title = '查看用户'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delUser(row.id)
      ElMessage.success('删除成功')
      getUserList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除用户失败', error)
    ElMessage.error('删除用户失败')
  }
}

// 批量删除用户
const handleBatchDelete = async (rows) => {
  try {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delUser(row.id)))
      ElMessage.success('批量删除成功')
      getUserList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除用户失败', error)
    ElMessage.error('批量删除用户失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    if (dialogConfig.isEdit) {
      // 编辑
      await updateUser(data)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addUser(data)
      ElMessage.success('添加成功')
    }
    
    // 刷新列表
    getUserList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 切换到编辑模式
const switchToEdit = () => {
  dialogConfig.title = '编辑用户'
  dialogConfig.isEdit = true
  dialogConfig.isView = false
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>

<template>
  <div class="user-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @add="handleAdd"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getUserList"
      />
    </el-card>
    
    <!-- 表单对话框 - 添加/编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    />
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #createTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">编辑</el-button>
        </div>
      </template>
    </dialog-form>
  </div>
</template>

<style scoped>
.user-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 